package com.eims.sls_app.ui;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.toolbox.RequestParams;
import com.contans.view.BallInfo;
import com.contans.view.MainFenxiVo;
import com.eims.ball.info.adapter.MyFragmentPagerAdapter;
import com.eims.ball.info.fragment.FenxiOneFragment;
import com.eims.ball.info.fragment.PeilvTwoFragment;
import com.eims.sls_app.dataaccess.Lottery;
import com.eims.sls_app.dataaccess.Schemes;
import com.eims.sls_app.dataaccess.Users;
import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.ImageManager;
import com.eims.sls_app.view.XCRoundImageView;

import android.annotation.SuppressLint;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import bls.juejin.cn.R;

public class MainLiveixActivity extends MyFragmentActivity implements OnClickListener {
	private String TAG = "MainFaHongbaoActivity";
	private ViewPager mPager;
	private ImageView ivBottomLine;
	private TextView tvTabActivity, tvTabGroups;
	private ArrayList<Fragment> fragmentsList;
	private int currIndex = 0;
	private int bottomLineWidth;
	private int offset = 0;
	private int position_one;
	private int position_two;
	private int position_three;
	private Resources resources;
	private MyFragmentPagerAdapter adaper;
	private String auth;
	private String opt, info, time, imei, crc;
	private ImageButton ibBack;

	private TextView tvTitle;

	private MainFenxiVo mainFenxiVo;
	private WebView webView;
	private GetinfoMyHandler getinfoMyHandler;

	private String webViewId;
	private String id = "";

	private LinearLayout lrWebview;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main_live_fenxi_layout);
		resources = getResources();
		mainFenxiVo = App.mainFenxiVo;
		getinfoMyHandler = new GetinfoMyHandler();

		Bundle bundle = getIntent().getExtras();
		id = bundle.getString("id");
		InitWidth();
		InitTextView();
		InitViewPager();
	}

	@Override
	public Resources getResources() {
		// TODO Auto-generated method stub
		Resources res = super.getResources();
		Configuration config = new Configuration();
		config.setToDefaults();
		res.updateConfiguration(config, res.getDisplayMetrics());
		return res;
	}

	private void InitTextView() {
		Log.e("11", id);
		tvTabActivity = (TextView) findViewById(R.id.tv_tab_activity);
		tvTabGroups = (TextView) findViewById(R.id.tv_tab_groups);
		ibBack = (ImageButton) findViewById(R.id.btn_back_con);
		ibBack.setOnClickListener(this);
		tvTabActivity.setOnClickListener(new MyOnClickListener(0));
		tvTabGroups.setOnClickListener(new MyOnClickListener(1));

		tvTitle = (TextView) findViewById(R.id.tv_title);

		tvTitle.setText(mainFenxiVo.getRow().getLeaguename());
		lrWebview = (LinearLayout) findViewById(R.id.lr_webView);
		webView = (WebView) findViewById(R.id.webView);
		WebSettings webSettings = webView.getSettings();

		WindowManager wm = getWindowManager();
		int width = wm.getDefaultDisplay().getWidth();// 获取屏幕宽度
		LinearLayout.LayoutParams ppl = (LayoutParams) lrWebview.getLayoutParams();
		ppl.width = width;
		ppl.height = (width * 445) / 790;
		lrWebview.setLayoutParams(ppl);// 把banner图的高度设为此宽度值
		Log.e("*----", ppl.width + "," + ppl.height);
		// 让WebView能够执行javaScript
		webSettings.setJavaScriptEnabled(true);
		// 让JavaScript可以自动打开windows
		// 将图片调整到合适的大小
		webSettings.setUseWideViewPort(true);
		webSettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
		webSettings.setLoadWithOverviewMode(true);
		// 设置支持缩放
		webSettings.setBuiltInZoomControls(false);
		// webSettings.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
		GetinfoMyAsynTask asynTask = new GetinfoMyAsynTask();
		asynTask.execute();
	}

	private void InitViewPager() {

		Log.e("11", "4");
		mPager = (ViewPager) findViewById(R.id.vPager);
		fragmentsList = new ArrayList<Fragment>();

		if (fragmentsList != null) {
			fragmentsList.clear();
			Log.e("11", "14");
		}
		// Fragment activityfragment = TestFragment.newInstance("Hello",paramMap);
		// Fragment groupFragment = TestFragment.newInstance("Hello Group.",paramMap2);

		//
		// fragmentsList.add(activityfragment);
		// fragmentsList.add(groupFragment);

		Fragment activityfragment =FenxiOneFragment.newInstance(mainFenxiVo.getRow().getItemId(),
				mainFenxiVo.getRow().getHid(), mainFenxiVo.getRow().getGid(), mainFenxiVo.getRow().getHn(),
				mainFenxiVo.getRow().getGn());
		Fragment groupFragment = PeilvTwoFragment.newInstance(mainFenxiVo.getRow().getItemId(), mainFenxiVo.getRow().getHid(),
				mainFenxiVo.getRow().getGid(), mainFenxiVo.getRow().getHn(), mainFenxiVo.getRow().getGn());

		fragmentsList.add(activityfragment);
		fragmentsList.add(groupFragment);

		adaper = new MyFragmentPagerAdapter(getSupportFragmentManager(), fragmentsList);
		adaper.notifyDataSetChanged();
		mPager.setAdapter(adaper);

		mPager.setCurrentItem(0);
		mPager.setOnPageChangeListener(new MyOnPageChangeListener());
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		fragmentsList.clear();
		Log.e("1", "5");
		super.onDestroy();
	}

	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		Log.e("1", "6");
		super.onStop();
	}

	@Override
	public void onPause() {
		Log.e("1", "7");
		// TODO Auto-generated method stub
		super.onPause();
	}

	private void InitWidth() {
		Log.e("11", "2");
		ivBottomLine = (ImageView) findViewById(R.id.iv_bottom_line);
		int h = MainLiveixActivity.this.getResources().getDisplayMetrics().heightPixels;
		int w = MainLiveixActivity.this.getResources().getDisplayMetrics().widthPixels;
		LayoutParams lp;
		lp = (LayoutParams) ivBottomLine.getLayoutParams();
		lp.width = w / 2;
		ivBottomLine.setLayoutParams(lp);

		bottomLineWidth = ivBottomLine.getLayoutParams().width;
		Log.d(TAG, "cursor imageview width=" + bottomLineWidth);
		DisplayMetrics dm = new DisplayMetrics();
		this.getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenW = dm.widthPixels;
		offset = (int) ((screenW / 2.0 - bottomLineWidth) / 2);

		position_one = (int) (screenW / 2.0);
		position_two = position_one * 2;

	}

	public class MyOnClickListener implements View.OnClickListener {
		private int index = 0;

		public MyOnClickListener(int i) {
			index = i;
		}

		@Override
		public void onClick(View v) {
			mPager.setCurrentItem(index);
		}
	};

	public class MyOnPageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageSelected(int arg0) {
			Animation animation = null;
			switch (arg0) {
			case 0:
				if (currIndex == 1) {
					animation = new TranslateAnimation(position_one, 0, 0, 0);
					tvTabGroups.setTextColor(resources.getColor(R.color.main_peilv));
				}
				tvTabActivity.setTextColor(resources.getColor(R.color.main_red));
				break;
			case 1:
				if (currIndex == 0) {
					animation = new TranslateAnimation(0, position_one, 0, 0);
					tvTabActivity.setTextColor(resources.getColor(R.color.main_peilv));
				}
				tvTabGroups.setTextColor(resources.getColor(R.color.main_red));
				break;

			}
			currIndex = arg0;
			animation.setFillAfter(true);
			animation.setDuration(300);
			ivBottomLine.startAnimation(animation);
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_back_con:
			finish();
			break;

		default:
			break;
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		Log.e("xxxa", "tiqu---------");

		outState.putString("lotterysId", App.lotterysId);

		outState.putInt("schemeId", App.schemeId);

		outState.putSerializable("user", App.user);
		outState.putSerializable("mainFenxiVo", App.mainFenxiVo);

		outState.putSerializable("scheme", App.scheme);
		outState.putSerializable("lottery", App.lottery);

		super.onSaveInstanceState(outState);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		Log.e("xxxa", "tiqu---------11");
		if (savedInstanceState != null) {

			App.lotterysId = savedInstanceState.getString("lotterysId");

			App.schemeId = savedInstanceState.getInt("schemeId");

			App.scheme = (Schemes) savedInstanceState.getSerializable("scheme");
			App.user = (Users) savedInstanceState.getSerializable("user");
			App.mainFenxiVo = (MainFenxiVo) savedInstanceState.getSerializable("mainFenxiVo");

			App.lottery = (Lottery) savedInstanceState.getSerializable("lottery");

		}
	}

	class GetinfoMyAsynTask extends AsyncTask<Integer, Integer, String> {

		String error = "1";

		@Override
		protected String doInBackground(Integer... params) {

			opt = "111";
			time = RspBodyBaseBean.getTime();
			imei = RspBodyBaseBean.getIMEI(MainLiveixActivity.this);

			info = id;
			String key = App.key;
			crc = RspBodyBaseBean.getCrc(time, imei, key, info, "-1");
			auth = RspBodyBaseBean.getAuth(crc, time, imei, "-1");
			String[] values = { opt, auth, info };
			Log.i(TAG, "xiadan" + RequestParams.convertParams(MainLiveixActivity.this, opt, info));
			String result = HttpUtils.doPost(App.names, values, App.path);
			Log.e(TAG, "xiadan-----" + result);
			webViewId = result;

			return error;
		}

		@Override
		protected void onPostExecute(String result) {
			getinfoMyHandler.sendEmptyMessage(Integer.parseInt(result));
			super.onPostExecute(result);
		}
	}

	@SuppressLint("HandlerLeak")
	class GetinfoMyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case 1:
				// WebView加载web资源
				webView.loadUrl("http://888.qcai888.cn/leisu/ls2.html?id=" + webViewId);
				// 覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
				webView.setWebViewClient(new WebViewClient() {
					@Override
					public boolean shouldOverrideUrlLoading(WebView view, String url) {
						// TODO Auto-generated method stub
						// 返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
						view.loadUrl(url);
						return true;
					}
				});
				break;

			default:
				Toast.makeText(MainLiveixActivity.this, "网络异常，获取信息失败。", Toast.LENGTH_SHORT).show();
				break;
			}
			super.handleMessage(msg);
		}
	}

}
